/* lifeprog.c a demo for lino */
#include "lino.h"
#include "lifeprog.h"
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>  
char state[EDGE+2][EDGE+2];
char newstate[EDGE][EDGE];
char trans[6]={0,0,0,1,1,0};
FILE *fp[8];
main(int argc, char ** argv)
{
   int i,count;
   for(i=NORTHIN;i<=WESTOUT;i++){
	printf("open %s chan %d %s\n",argv[i],i,(i&1?"r":"w"));
	fp[i]=fopen(argv[i], (i&1?"r":"w"));
	if(fp[i]!= NULL)printf("opened %s \n",argv[i]);
	else{
		printf("could not open %s",argv[i]);exit(1);
	}
	}
   for(count=0;count<10000;count++)
   {fprintf(stderr,"run %d\n",count);
	writestates();
	readstates();
	updatestates();
   }
}

updatestates()
{
	int i,j;
	for(i=0;i<EDGE;i++)
	for(j=0;j<EDGE;j++)newstate[i][j]=trans[state[i][j+1]+state[i+1][j+1]+state[i+2][j+1]+state[i+1][j]+state[i+1][j+2]];
	for(i=0;i<EDGE;i++)
	for(j=0;j<EDGE;j++)state[i+1][j+1]=newstate[i][j];
}
writestates()
{
	char westbuf[EDGE];char eastbuf[EDGE];int i;
	fwrite( &(state[1][1]),1,EDGE,fp[NORTHOUT]);fprintf(stderr,"wrote north\n");
	fwrite( &(state[EDGE][1]),1,EDGE,fp[SOUTHOUT]);
	for(i=0;i<EDGE;i++){westbuf[i]=state[i+1][1];eastbuf[i]= state[i+1][EDGE];}
	fwrite(eastbuf,1,EDGE,fp[EASTOUT]);
	fwrite( westbuf,1,EDGE,fp[WESTOUT]);fprintf(stderr,"wrote west\n");
}
readstates()
{
	char westbuf[EDGE];char eastbuf[EDGE];int i;
	fread( &(state[1][1]),1,EDGE,fp[NORTHOUT]);fprintf(stderr,"read north\n");
	fread( &(state[EDGE][1]),1,EDGE,fp[SOUTHOUT]);
	fread(eastbuf,1,EDGE,fp[ EASTOUT]);
	fread( westbuf,1,EDGE,fp[WESTOUT]);fprintf(stderr,"read west\n");
	for(i=0;i<EDGE;i++){state[i+1][0]=westbuf[i];state[1+i][EDGE+1]=eastbuf[i];}
	
}
